package comman.duke 
{
	import flash.text.TextField;
	import flash.text.TextFormat;
	/**
	 * ...
	 * @author jerry.d
	 */
	public class FloatHint 
	{
		public var name:String = 'floathint';
		private var frameItem:FrameItem;
		private static var TF_CNT:int = 0;
		public function FloatHint() 
		{
			this.init();
			this.frameItem = new FrameItem(this.name, this.update);
		}
		
		private var colors:Object = {
			0 : 0x000000,//normal
			1 : 0x00ff00,//remind
			2 : 0xffff00,//gain
			3 : 0xff0000//warning
		}
		private static const DURATION:int = 2000;
		private static var startY:int;
		private static var targetY:int;
		private static const DISTANCE:int = 100;
		private function init():void{
			startY = GameVars.Stage_Height >> 1;
			targetY  = startY - DISTANCE;
		}
		private static var tFormat:TextFormat = new TextFormat('Arial', 24, 0xff0000,true);
		public function show(msg:String, x:int = -1, y:int = -1 ):void{
			var tf:TextField = gain();
			tf.text = msg;
			if ( x == -1){
				tf.x = GameVars.Stage_Width - tf.width >> 1;
			}else{
				tf.x = x;
			}
			
			if ( y == -1){
				tf.y = startY;
			}else{
				tf.y = y;
			}
			
			usingMap[tf.name] = tf;
			usingTime[tf.name] = 0;
			GameVars.STAGE.addChild(tf);
			
			if ( !FrameMgr.Instance.has(this.name)){
				FrameMgr.Instance.add(this.frameItem);
			}
		}
		private var usingMap:Object = {};
		private var usingTime:Object = {};
		public function update(delta:int):void{
			var tf:TextField;
			var usedTime:int;
			var got:Boolean = false;
			var goDistance:int = 0;
			for (var key:String in usingTime){
				tf = usingMap[key];
				usedTime = usingTime[key];
				usedTime += delta
				if ( usedTime >= DURATION ){
					delete usingMap[key];
					delete usingTime[key];
					GameVars.STAGE.removeChild(tf);
					reclaim(tf);
				}else{
					got = true;
					usingTime[key] = usedTime;
					tf.y = startY - usedTime / DURATION * DISTANCE  ;
				}
			}
			if (!got){
				FrameMgr.Instance.remove( this.name );
			}
		}
		
		private static var _pool:Vector.<TextField> = new Vector.<TextField>();
		private static function reclaim(tf:TextField):void{
			if ( _pool.indexOf(tf) == -1){
				_pool.push(tf);
			}
		}
		
		private static function gain():TextField{
			if ( _pool.length != 0 ){
				return _pool.pop();
			}
			var tf:TextField = new TextField();
			tf.name = 'tf_' + TF_CNT;
			tf.autoSize = 'center';
			tf.defaultTextFormat = tFormat;
			tf.setTextFormat(tFormat);
			TF_CNT++;
			return tf;
		}
		
		private static var _instance:FloatHint;
		public static function get Instance():FloatHint{
			if ( FloatHint._instance == null ){
				FloatHint._instance = new FloatHint();
			}
			return FloatHint._instance;
		}
	}

}